package com.web.visitors_backend.controller;

import cn.hutool.core.date.DateUtil;
import com.google.zxing.WriterException;
import com.web.visitors_backend.common.Response;
import com.web.visitors_backend.model.Visitor;
import com.web.visitors_backend.model.VisitorRequest;
import com.web.visitors_backend.service.VisitorService;
import com.web.visitors_backend.utils.QRCodeGenerator;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.UUID;

@Slf4j
@RestController
@RequestMapping("/visitors")
@CrossOrigin(origins = "*")
public class VisitorController {
    @Autowired
    private VisitorService visitorService;

    @GetMapping("/getAll")
    public Response<?> getAllVisitors() {
        return Response.newSuccess(visitorService.getAllVisitors());
    }

    @GetMapping("/getVisitorsFromDateRange")
    public Response<?> getVisitorsFromDateRange(@RequestParam String startTime, @RequestParam String endTime) {

        Date start = DateUtil.parse(startTime, DateTimeFormatter.ISO_DATE_TIME);
        Date end = DateUtil.parse(endTime, DateTimeFormatter.ISO_DATE_TIME);
        return Response.newSuccess(this.visitorService.getVisitorsFromDateRange(start, end));
    }

    /**
     * 新来访人员登记
     *
     * @param visitorRequest
     * @return
     */
    @PostMapping("/add")
    public Response<?> addVisitor(@RequestBody VisitorRequest visitorRequest) {
        Visitor visitor = new Visitor();
        BeanUtils.copyProperties(visitorRequest, visitor);
        // 获取当前时刻
        visitor.setTime(new Date());
        // 二维码路径
        String currentDir = System.getProperty("user.dir");
        String qrCodeFilename = UUID.randomUUID() + ".png";
        String QRCodeFilepath = currentDir + "/" + qrCodeFilename;
        try {
            QRCodeGenerator.generateQRCodeImage(QRCodeFilepath, QRCodeFilepath);
            log.info("QRCodeFilepath:{}", qrCodeFilename);
            visitor.setQr_code(qrCodeFilename);
            visitorService.save(visitor);
            return Response.newSuccess(visitor);//这里不返回vo是因为前端要拿二维码的地址
        } catch (WriterException | IOException e) {
            log.error("生成二维码失败:{}", e.getMessage());
            return Response.newError("生成二维码失败");
        }
    }


    @GetMapping("/getQRCode")
    public void getQRCode(@RequestParam String qrCodeFilename, HttpServletResponse response) {
        String currentDir = System.getProperty("user.dir");
        String QRCodeFilepath = currentDir + "/" + qrCodeFilename;
        File file = new File(QRCodeFilepath);
        try {
            byte[] image = Files.readAllBytes(file.toPath());
            response.setContentType("application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + qrCodeFilename);
            //写入响应
            response.getOutputStream().write(image);
            response.getOutputStream().flush();
        } catch (IOException e) {
            log.error("读取失败:{}", e.getMessage());
        }

    }


}
